<?php
/**
 * 유틸리티 - Captcha 이미지 생성자
 *
 * @package    util
 * @subpackage captcha
 *
 * @version 1.0
 * @author    jylee3@simplexi.com
 */
class utilCaptchaGenerator
{
    /**
     * Captcha 이미지 생성
     *
     * @param    Integer    $iWidth
     * @param    Integer    $iHeight
     * @param    Integer    $iCharLen
     * @param    String    $sImageType
     * @param    String    $sTTFFile
     *
     * @return    utilCaptchaImage
     */
    public function generateCaptchaImages($iWidth, $iHeight, $iCharLen, $sImageType, $sTTFFile)
    {
        if(empty($sTTFFile))    $sTTFFile = $this->defaultFontFile();

        $sCode = $this->generateCode($iCharLen);

        /* font size will be 75% of the image height */
        $iFontSize = $iHeight * 0.75;

        $rImage = imagecreate($iWidth, $iHeight) or die('Cannot initialize new GD image stream');

        /* set the colours */
        $background_color = imagecolorallocate($rImage, 255, 255, 255);
        $text_color = imagecolorallocate($rImage, 20, 40, 100);
        $noise_color = imagecolorallocate($rImage, 100, 120, 180);

        /* generate random dots in background */
        for ($i=0; $i<($iWidth*$iHeight)/3; $i++) {
            imagefilledellipse($rImage, mt_rand(0,$iWidth), mt_rand(0,$iHeight), 1, 1, $noise_color);
        }

        /* generate random lines in background */
        for ($i=0; $i<($iWidth*$iHeight)/150; $i++) {
            imageline($rImage, mt_rand(0,$iWidth), mt_rand(0,$iHeight), mt_rand(0,$iWidth), mt_rand(0,$iHeight), $noise_color);
        }
        /* create textbox and add text */
        $aTextbox = imagettfbbox($iFontSize, 0, $sTTFFile, $sCode) or die('Error in imagettfbbox function');

        $iX = ($iWidth - $aTextbox[4])/2;
        $iY = ($iHeight - $aTextbox[5])/2;

        imagettftext($rImage, $iFontSize, 0, $iX, $iY, $text_color, $sTTFFile, $sCode) or die('Error in imagettftext function');

        return new utilCaptchaImage($iWidth, $iHeight, $sImageType, $sCode, $rImage);
    }

    /**
     * Captcha 코드 생성
     *
     * @param    Integer    $iCharLen
     *
     * @return    String
     */
    protected function generateCode($iCharLen)
    {
        /* list all possible characters, similar looking characters and vowels have been removed */
        $sPossible = '23456789bcdfghjkmnpqrstvwxyz';
        $iPossible = strlen($sPossible);
        $sCode = '';

        for ($i=0; $i<$iCharLen; $i++) {
            $sCode .= substr($sPossible, mt_rand(0, $iPossible-1), 1);
        }

        return $sCode;
    }

    /**
     * Captcha 기본 폰트 반환
     *
     * @return    String
     */
    protected function defaultFontFile()
    {
        return FW_DIR_FRAMEWORK_UTIL.DS.'Captcha'.DS.'monofont.ttf';
    }
}
